#!/usr/bin/env python
import os,sys,time, os.path

# add self to search path for testing
if __name__ == '__main__':
    sys.path.append("../python_modules")

def commonpath(l1, l2, common=[]):
    if len(l1) < 1: return (common, l1, l2)
    if len(l2) < 1: return (common, l1, l2)
    if l1[0] != l2[0]: return (common, l1, l2)
    return commonpath(l1[1:], l2[1:], common+[l1[0]])

def pathsplit(path):
    return path.split(os.path.sep)


def relpath(base_path, new_file_or_directory):
    """
    """
    (common,l1,l2) = commonpath(pathsplit(base_path), 
                                pathsplit(new_file_or_directory))
    p = []
    if len(l1) > 0:
        p = [ '../' * len(l1) ]
    p = p + l2
    if len(p) is 0:
        return "."
    return os.path.join( *p )



        
def unit_test():
    a= "../perl_modules"
    b= "./ortho_species.py"
    a = os.path.abspath(a)
    b = os.path.abspath(b)
    print relpath(a,b)
    print a, b

    b = "/"
    print relpath(a,b)
    print a, b
    
if __name__ == '__main__':
    unit_test()
